<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Excel;
class BaseController extends Controller{

    public function build_pager_data($paginate){
        $paginate = $paginate->toArray();
        $pager = [
            'total' => $paginate['total'],
            'per_page' => $paginate['per_page'],
            'current_page' => $paginate['current_page'],
            'last_page' => $paginate['last_page'],
            'data' => $paginate['data']
        ];
        return $pager;
    }

    public function modelExist($model_class,$data,$id = 0){
        $exist = $model_class::where($data)->first();
        if($exist && $id > 0){
            return $exist->id != $id;
        }
        return $exist;
    }


    public function export($list,$headers,$getrow_callback){
        //清空缓冲区
        ob_clean();
        Excel::create(date('YmdHis').'_导出结果', function($excel) use($list,$headers,$getrow_callback) {
             $excel->sheet('Sheet1', function($sheet) use($list,$headers,$getrow_callback) {
                 $sheet->row(1,$headers);
                 $row = 2;
                 foreach ($list as $model) {
                     $data = call_user_func($getrow_callback,$model);
                     $sheet->row($row++,$data);
                 }
             });
        })->download('xls');
    }

    public function index_model_list($model_class_name,$columns,$request,$build_condition_callback,$export_callback){

        $export = $request->get('export',0);//导出
        $mode = $request->get('mode',0); //0分页查询 , 1不分页

        // $model_class = get_class($model_class_name);
        $builder = $model_class_name::where([]);

        call_user_func($build_condition_callback,$builder);

        $builder->orderBy('id','desc');

        if($export == 1){
            $list = $builder->get();
            $this->export($list,$columns,function($model) use($export_callback){
                return call_user_func($export_callback,$model);
            });
        }else{
            if($mode == 0){
                $pager = $this->build_pager_data($builder->paginate(10));
                return response()->json(json_success($pager));
            }
            elseif($mode == 1){
                $list = $builder->get();
                return response()->json(json_success($list));
            }
        }
    }
}
